package com.yztc.administrator.meishi.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.lidroid.xutils.ViewUtils;
import com.yztc.administrator.meishi.JsonGet;
import com.yztc.administrator.meishi.R;
import com.yztc.administrator.meishi.activity.VideoActivity;
import com.yztc.administrator.meishi.adapter.MeiAdapter;
import com.yztc.administrator.meishi.bean.MeiPai;
import com.yztc.administrator.meishi.construct.Path;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HotFragment extends Fragment {

    private View view = null;
    private List<MeiPai> list;
    private Message msg;
    int count = 20;

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //接受数据，创建适配器
            list = (List<MeiPai>) msg.obj;
            MeiAdapter adapter = new MeiAdapter(getContext());
            adapter.setData(list);
            mPull.setAdapter(adapter);

        }
    };
    private String path;//json地址
    private PullToRefreshGridView mPull;
    private GridView gridView;

    public HotFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建布局填充器
        LayoutInflater inflater = getActivity().getLayoutInflater();
        view = inflater.inflate(R.layout.fragment_hot, (ViewGroup) getActivity().findViewById(R.id.vp), false);

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        ViewGroup p = (ViewGroup) view.getParent();
        if (p != null) {
            p.removeAllViewsInLayout();
        }
        ViewUtils.inject(this, view);

        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //fragment可见时执行加载数据或者进度条等
        } else {
            //不可见时不执行操作
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //找到控件
        mPull = (PullToRefreshGridView) view.findViewById(R.id.pull_refresh_grid);
        mPull.setScrollingWhileRefreshingEnabled(true);
        //得到gridview，并且设置每行数目
        gridView = mPull.getRefreshableView();
        gridView.setNumColumns(2);
        new Thread() {
            @Override
            public void run() {
                Bundle bundle = getArguments();
                path = bundle.getString("path");
                List<MeiPai> meiPais = JsonGet.jsonMedia(path);
                msg = Message.obtain();
                msg.obj = meiPais;
                mHandler.sendMessage(msg);
            }
        }.start();
        //设置上啦加载下拉刷新
        loadLisener();
        //设置点击
        pullOnClick ();
    }

    /* *
       * @author: ZTC
       * @Description: 设置mpull点击
       * @data:  2016/9/22  13:14
       * @version: V1.0
       */
    private void pullOnClick() {
        mPull.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取相应位置对象
                MeiPai meiPai = (MeiPai) gridView.getItemAtPosition(position);
                //判断video是否非空
                if (meiPai.getVideo() != null){
                    Intent intent = new Intent(getActivity(), VideoActivity.class);
                    intent.putExtra("url",meiPai.getVideo());
                    intent.putExtra("caption", meiPai.getCaption());
                    intent.putExtra("likes_count",meiPai.getLikes_count());
                    intent.putExtra("screen_name",meiPai.getScreen_name());
                    startActivity(intent);
                }else {
                    Toast.makeText(getActivity(), "此类型无视频", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    /* *
       * @author: ZTC
       * @Description: 设置上啦刷新下拉加载
       * @data:  2016/9/22  13:13
       * @version: V1.0
       */
    private void loadLisener() {
        //设置上下拉模式
        mPull.setMode(PullToRefreshBase.Mode.BOTH);
        mPull.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            private String s2;
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                //添加刷新时间
                String label = DateUtils.formatDateTime(
                        getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy()
                        .setLastUpdatedLabel(label);
                //下拉刷新直接刷新数据
                    new Thread() {
                        @Override
                        public void run() {
                            List<MeiPai> meiPais = JsonGet.jsonMedia(path);
                            msg = Message.obtain();
                            msg.obj = meiPais;
                            mHandler.sendMessage(msg);
                        }
                    }.start();
                mPull.onRefreshComplete();//停止刷新操作
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                //添加刷新时间
                String label = DateUtils.formatDateTime(
                        getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy()
                        .setLastUpdatedLabel(label);
                //拼接字符串
                StringBuilder builder = new StringBuilder();
                final String s = builder.append(path).append(Path.str).toString();
                count += 20;
                String s1 = Integer.toString(count);
                //替换字符串
                s2 = s.replaceAll("%d", s1);
                //每次刷新增加显示条目
                if (count <= 200) {
                    new Thread() {
                        @Override
                        public void run() {
                            List<MeiPai> meiPais = JsonGet.jsonMedia(s2);
                            msg = Message.obtain();
                            msg.obj = meiPais;
                            mHandler.sendMessage(msg);
                        }
                    }.start();
                } else {
                    Toast.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                }
                mPull.onRefreshComplete();//停止刷新操作
            }
        });
    }

}